<?php

namespace app\bll;

use app\validate\UserGrade as ValidateUserGrade;
use core\attribute\Template;
use Exception;
use support\Db;

class UserGrade
{

    /**
     * 查找等级信息
     *
     * @param integer $id
     * @return array
     */
    public  function find(int $id): array
    {
        $data =  Db::table('frame_user_grade')
            ->where('id', '=', $id)
            ->first();
        return $data === null ? [] : get_object_vars($data);
    }

    /**
     * 查询会员等级
     *
     * @return array
     */
    public function select(): array
    {
        return  Db::table('frame_user_grade')
            ->orderBy('points')
            ->get()
            ->map(function ($value) {
                return (array)$value;
            })
            ->toArray();
    }


    /**
     * 增加等级
     *
     * @param array $data
     * @return integer
     */
    public function add(array $data): int
    {
        $ValidateUserGrade = new ValidateUserGrade();
        if (!$ValidateUserGrade->check($data)) {
            throw new Exception($ValidateUserGrade->getSimpleError());
        }


        return  Db::table('frame_user_grade')
            ->insertGetId($data);
    }


    /**
     * 编辑
     *
     * @param integer $id
     * @param array $data
     * @return integer
     */
    public function edit(int $id, array $data): int
    {
        $ValidateUserGrade = new ValidateUserGrade();
        if (!$ValidateUserGrade->check($data)) {
            throw new Exception($ValidateUserGrade->getSimpleError());
        }

        return  Db::table('frame_user_grade')
            ->where('id', '=', $id)
            ->update($data);
    }

    /**
     * 删除
     *
     * @param integer $id
     * @return integer
     */
    public function delete(int $id): int
    {
        return  Db::table('frame_user_grade')
            ->where('id', '=', $id)
            ->delete();
    }


    /**
     * 当前积分所在会员等级区间
     *
     * @param integer $points
     * @return array
     */
    #[Template]
    public function nowGradeRange(int $points): array
    {
        $grades = $this->select();
        $nowGrade = [];
        $nextPoints = 0;
        foreach ($grades as $key => $value) {
            if ($points >= $value['points']) {
                $nowGrade = $value;
                if ($key == count($grades) - 1) {
                    $nextPoints = $value['points'];
                } else {
                    $nextPoints = $grades[$key + 1]['points'];
                }
            }
        }
        $nowGrade['nextPoints'] = $nextPoints;
        return $nowGrade;
    }
}
